package com.handa.common.config;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;


@Configuration
public class SnowflakeConfig {
    private long workerId = 0;  // 工作机器ID
    private long datacenterId = 1; // 数据中心ID
    private Snowflake snowflake;

    @PostConstruct
    public void init() {
        try {
            // 获取本机的workerId
            workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
        } catch (Exception e) {
            workerId = NetUtil.getLocalhostStr().hashCode();
        }

        // 如果workerId超过范围(0~31)，则取模
        workerId = workerId & 31;

        snowflake = IdUtil.getSnowflake(workerId, datacenterId);
    }

    public synchronized long snowflakeId() {
        return snowflake.nextId();
    }

    public synchronized String snowflakeIdStr() {
        return snowflake.nextIdStr();
    }
}